/**
 * 
 */
package com.youxin.cpcenter.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.youxin.busfoundation.bean.BusinessMessages;
import com.youxin.busfoundation.bean.leads.LeadsStatTotalBean;
import com.youxin.busfoundation.common.BusinessDataException;
import com.youxin.busfoundation.enums.CapitalFlag;
import com.youxin.busfoundation.enums.EnterpriseIdentityType;
import com.youxin.busfoundation.enums.OrderPayTypeEnums;
import com.youxin.busfoundation.enums.ServiceType;
import com.youxin.busfoundation.utils.DateTimeBusUtils;
import com.youxin.cpcenter.dao.TbEntMemberIdentifyCapitalHisMapper;
import com.youxin.cpcenter.dao.TbEntMemberIdentifyCapitalListMapper;
import com.youxin.cpcenter.dao.TbEntMemberIdentifyCapitalMapper;
import com.youxin.cpcenter.dao.TbEntMemberIdentifyMapper;
import com.youxin.cpcenter.dao.TbEntMemberInfoMapper;
import com.youxin.cpcenter.model.TbEntMemberIdentify;
import com.youxin.cpcenter.model.TbEntMemberIdentifyCapital;
import com.youxin.cpcenter.model.TbEntMemberIdentifyCapitalHis;
import com.youxin.cpcenter.model.TbEntMemberIdentifyCapitalList;
import com.youxin.cpcenter.model.TbOrderInfo;
import com.youxin.cpcenter.service.CapitalService;
import com.youxin.cpcenter.service.CouponService;
import com.youxin.foundation.db.utils.KeyGenerationUtils;
import com.youxin.foundation.utils.JsonUtils;

/**
 * @description 企业资产合同更新服务
 *              ((CapitalService)AopContext.currentProxy()).recharge(orderInfo,
 *              entIdentifyId, companyUid, orderType);
 * @author yingde.cao
 * @date 2017年12月12日
 * @version 1.0
 */
@Service("capitalService")
public class CapitalServiceImpl extends BaseServiceImpl implements CapitalService {

	@Autowired
	private TbEntMemberIdentifyCapitalMapper tbEntMemberIdentifyCapitalMapper;

	@Autowired
	private TbEntMemberIdentifyCapitalListMapper tbEntMemberIdentifyCapitalListMapper;
	@Autowired
	private TbEntMemberIdentifyCapitalHisMapper tbEntMemberIdentifyCapitalHisMapper;
	@Autowired
	private CouponService couponService;
	@Autowired
	private TbEntMemberIdentifyMapper tbEntMemberIdentifyMapper;
	
	@Autowired
	private TbEntMemberInfoMapper tbEntMemberInfoMapper;
	

//	public TbEntMemberIdentifyCapital queryCapital(long entIdentifyId)
//	{
//		return tbEntMemberIdentifyCapitalMapper.selectByPrimaryKey(entIdentifyId);
//	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.youxin.cpcenter.service.CapitalService#isExpires()
	 */
	@Override
	public boolean isAvailable(long entIdentifyId) {
		TbEntMemberIdentifyCapital capital = tbEntMemberIdentifyCapitalMapper.selectByPrimaryKey(entIdentifyId);
		long expiresTime = capital.getExpiresTime().getTime();
		return expiresTime > System.currentTimeMillis();
	}
	
	/**
	 * 是否能够升级,如果是VIP表示不能升级,普通版可以升级
	 * @description 
	 * @param entIdentifyId
	 * @return
	 */
	public boolean isCanUpgrade(long entIdentifyId)
	{
		TbEntMemberIdentify capital = tbEntMemberIdentifyMapper.selectByPrimaryKey(entIdentifyId);
		return capital.getIdentyType().shortValue()==EnterpriseIdentityType.Normal.getValue();
	}
	
	public boolean calculateUpgradeMoney(long entIdentifyId)
	{
		//TbEntMemberIdentifyCapital capital=tbEntMemberIdentifyMapper.sele
		return true;
	}

	/**
	 * 判断是否可以使用
	 * 
	 * @description
	 * @param entIdentifyId
	 * @return
	 */
	public boolean isAvailableAndUpdate(long entIdentifyId) {
		TbEntMemberIdentifyCapital capital = getAvailableAndUpdateCapital(entIdentifyId);
		if (capital == null) {
			throw new BusinessDataException(BusinessMessages.SERVICE_EXPIRES);
		}
		return capital != null;
	}

	/**
	 * 是否能够添加线索
	 * 
	 * @description
	 * @param entIdentifyId
	 * @return boolean
	 */
	public boolean isCanAddLeads(long entIdentifyId) {
		TbEntMemberIdentifyCapital capital = getAvailableAndUpdateCapital(entIdentifyId);
		if (capital == null) {
			throw new BusinessDataException(BusinessMessages.SERVICE_EXPIRES);
		}
		if (capital.getLeadsNumber().intValue() <= 0) {
			throw new BusinessDataException(BusinessMessages.MEMBER_LEAD_NUMBER_LESS);
		}
		return true;
	}

	/**
	 * 是否能够添加会员
	 * 
	 * @description
	 * @param entIdentifyId
	 * @return boolean
	 */
	public boolean isCanAddMember(long entIdentifyId) {
		TbEntMemberIdentifyCapital capital = getAvailableAndUpdateCapital(entIdentifyId);
		if (capital == null) {
			throw new BusinessDataException(BusinessMessages.SERVICE_EXPIRES);
		}
		
		LeadsStatTotalBean totalBean=tbEntMemberInfoMapper.queryStatMemberNumber(entIdentifyId);
		if(totalBean.getTotal().intValue()>=capital.getTotalMemberNumber().intValue())
		{
			throw new BusinessDataException(BusinessMessages.MEMBER_NUMBER_FINISH);
		}		

		return true;
	}

	/**
	 * 检测并更新新的合约
	 * 
	 * @description
	 * @param entIdentifyId
	 *            认证ID
	 * @return boolean ((CapitalService)AopContext.currentProxy()).recharge(orderInfo,
 *              entIdentifyId, companyUid, orderType)
	 */
	public TbEntMemberIdentifyCapital getAvailableAndUpdateCapital(long entIdentifyId)
	{
		return ((CapitalService)AopContext.currentProxy()).checkedAvailableAndUpdateCapital(entIdentifyId);
	}
	
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public TbEntMemberIdentifyCapital checkedAvailableAndUpdateCapital(long entIdentifyId) {
		TbEntMemberIdentifyCapital capital = tbEntMemberIdentifyCapitalMapper.selectByPrimaryKey(entIdentifyId);
		if(capital==null){
			return null;
		}		
		long expiresTime = capital.getExpiresTime().getTime();
		long currentTime = System.currentTimeMillis();
		/**
		 * 是否过期了
		 */
		if (currentTime < expiresTime) {
			return capital;
		}
		long checkedTime = capital.getCheckedTime();
		/**
		 * 当前已经过期,不执行任何方法
		 */
		if (checkedTime >= expiresTime) {
			return null;
		}
		TbEntMemberIdentifyCapital capitalHistory=new TbEntMemberIdentifyCapital();
		BeanUtils.copyProperties(capital, capitalHistory);

		List<TbEntMemberIdentifyCapitalList> list = tbEntMemberIdentifyCapitalListMapper
				.selectByIdentifyId(entIdentifyId);
		TbEntMemberIdentifyCapitalList entity = null;
		/**
		 * 需要增加的金券
		 */
		BigDecimal couponAdded=new BigDecimal(0);
		if (!com.youxin.foundation.utils.ArrayUtils.isEmpty(list)) {
			List<TbEntMemberIdentifyCapitalList> expiresList = new ArrayList<>();
			for (TbEntMemberIdentifyCapitalList item : list) {
				if (item.getStartTime().getTime() >= expiresTime
						&& item.getExpiresTime().getTime() > System.currentTimeMillis()) {
					entity = item;
					break;
				} else {
					expiresList.add(item);
				}
			}
			/**
			 * 处理过期的合约
			 */
			for (TbEntMemberIdentifyCapitalList item : expiresList) {
				couponAdded=couponAdded.add(item.getCoupon());
				tbEntMemberIdentifyCapitalListMapper.deleteByPrimaryKey(item.getId());
			}
		}
		if (entity == null) {
			/**
			 * 金券需要累加
			 */
			if(couponAdded.compareTo(BigDecimal.ZERO)>0){
				couponService.increaseCoupon(entIdentifyId, couponAdded);
			}
			updateCaptialCheckedTimes(capital);
			return null;
		}else{
			couponAdded=couponAdded.add(entity.getCoupon());
			couponService.increaseCoupon(entIdentifyId, couponAdded);
		}
		int rowEffected = 0;		
		capital.setCheckedTime(0L);
		capital.setTotalLeadsNumber(entity.getTotalLeadsNumber());
		capital.setTotalMemberNumber(entity.getTotalMemberNumber());
		capital.setStartTime(entity.getStartTime());
		capital.setExpiresTime(entity.getExpiresTime());
		capital.setEnterpriseIdentyType(entity.getEnterpriseIdentyType());
		rowEffected = tbEntMemberIdentifyCapitalMapper.updateByPrimaryKeySelective(capital);
		if (rowEffected != 1) {
			throw new BusinessDataException(BusinessMessages.AUTO_UPGRADE_VERSION_ERROR);
		}
		/**
		 * 删除列表记录
		 */
		rowEffected = tbEntMemberIdentifyCapitalListMapper.deleteByPrimaryKey(entity.getId());
		if (rowEffected != 1) {
			throw new BusinessDataException(BusinessMessages.AUTO_UPGRADE_VERSION_ERROR);
		}
		/**
		 * 更新历史记录
		 */
		updateCaptalHistory(capitalHistory);
		return capital;
	}

	/**
	 * 更新资本的历史记录
	 * 
	 * @description
	 * @param capital
	 *            企业资本实体
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void updateCaptalHistory(TbEntMemberIdentifyCapital capital) {
		TbEntMemberIdentifyCapitalHis capitalHis = new TbEntMemberIdentifyCapitalHis();
		BeanUtils.copyProperties(capital, capitalHis);
		capitalHis.setId(KeyGenerationUtils.generateKey());
		capitalHis.setEntIdentifyId(capital.getId());
		capitalHis.setAddTime(System.currentTimeMillis());
		int rowEffected = tbEntMemberIdentifyCapitalHisMapper.insertSelective(capitalHis);
		if (rowEffected != 1) {
			throw new BusinessDataException(BusinessMessages.UPDATE_CAPTICAL_HISTORY_SERVICE_ERROR);
		}
	}


	/**
	 * 更新过期时间
	 * 
	 * @description
	 * @param capital
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	private boolean updateCaptialCheckedTimes(TbEntMemberIdentifyCapital capital) {
		TbEntMemberIdentifyCapital capitalUpdate = new TbEntMemberIdentifyCapital();
		capitalUpdate.setId(capital.getId());
		capitalUpdate.setCheckedTime(System.currentTimeMillis());
		int rowEffected = tbEntMemberIdentifyCapitalMapper.updateByPrimaryKeySelective(capitalUpdate);
		return false;
	}

	/**
	 * 更新表
	 * 
	 * @description
	 * @param serviceType
	 *            服务类型
	 * @param entIdentifyId
	 *            认证id
	 * @param amount
	 *            金额
	 * @param id
	 *            表主键id
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void updateServiceHistory(ServiceType serviceType, long entIdentifyId, BigDecimal amount, long memberId,
			String companyUid, long id) {
	}

	/**
	 * 企业版充值
	 * 
	 * @description
	 * @param orderInfo
	 * @param entIdentifyId
	 * @param companyUid
	 * @param memberId
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public void recharge(TbOrderInfo orderInfo) {
		if (orderInfo == null) {
			return;
		}
		OrderPayTypeEnums orderType=OrderPayTypeEnums.valueOf(orderInfo.getOrderType());
		if(orderType==null)
		{
			return;
		}		
		String jsonString = JsonUtils.objectToFasterxmlJsonString(orderInfo);
		logger.warn("升级版本:entIdentifyId=" + orderInfo.getEntIdentifyId() + "," + jsonString);
		EnterpriseIdentityType identifyType = null;
		if (orderType == OrderPayTypeEnums.PTVIP) {
			identifyType = EnterpriseIdentityType.Normal;
		} else if (orderType == OrderPayTypeEnums.VIP) {
			identifyType = EnterpriseIdentityType.Vip;
		}
		if (identifyType == null) {
			return;
		}
		TbEntMemberIdentifyCapital capital=tbEntMemberIdentifyCapitalMapper.selectByPrimaryKey(orderInfo.getEntIdentifyId());
		if(capital==null)
		{
			String json=JsonUtils.objectToFasterxmlJsonString(orderInfo);
			logger.error("CaptialService充值回调失败,没有找到Capital:"+json);
			return;
		}
		TbEntMemberIdentifyCapitalList lastCapitalList = tbEntMemberIdentifyCapitalListMapper
				.selectByIdentifyIdGetLast(orderInfo.getEntIdentifyId());
		TbEntMemberIdentifyCapitalList capitalList = new TbEntMemberIdentifyCapitalList();
		Date now = new Date();
		Date startTime = null;
		if (lastCapitalList != null) {
			startTime = lastCapitalList.getExpiresTime();
		} else {
			startTime = new Date();
			if(capital.getExpiresTime().getTime()>startTime.getTime())
			{
				startTime=capital.getExpiresTime();
			}
		}
		capitalList.setId(KeyGenerationUtils.generateKey());
		capitalList.setStartTime(startTime);
		Date expiresTime = DateTimeBusUtils.getExpiresYearDate(startTime);
		capitalList.setMemberId(orderInfo.getMemberId());
		capitalList.setExpiresTime(expiresTime);
		capitalList.setEntIdentifyId(orderInfo.getEntIdentifyId());
		capitalList.setAddTime(now.getTime());
		capitalList.setUpdateTime(now.getTime());
		capitalList.setCompanyUid("");
		capitalList.setCoupon(identifyType.getCoupon());
		capitalList.setTotalLeadsNumber(identifyType.getLeadsNumber());
		capitalList.setLeadsNumber(identifyType.getLeadsNumber());
		capitalList.setTotalMemberNumber(identifyType.getMemberNumber());
		capitalList.setMemberNumber(identifyType.getMemberNumber());
		capitalList.setEnterpriseIdentyType(identifyType.getValue());
		int rowEffected = tbEntMemberIdentifyCapitalListMapper.insertSelective(capitalList);
		if (rowEffected != 1) {
			throw new BusinessDataException(BusinessMessages.RECHARGE_UPGRADE_VERSION_ERROR);
		}
		TbEntMemberIdentifyCapital capitalUpdate=new TbEntMemberIdentifyCapital();
		capitalUpdate.setId(capital.getId());
		capitalUpdate.setCheckedTime(0L);
		rowEffected=tbEntMemberIdentifyCapitalMapper.updateByPrimaryKeySelective(capitalUpdate);
		if (rowEffected != 1) {
			throw new BusinessDataException(BusinessMessages.RECHARGE_UPGRADE_VERSION_ERROR);
		}
		updateCaptalHistory(capitalList, orderInfo.getOrderAmount());
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void updateCaptalHistory(TbEntMemberIdentifyCapitalList capitalList, BigDecimal money) {
		TbEntMemberIdentifyCapitalHis capitalHis = new TbEntMemberIdentifyCapitalHis();
		BeanUtils.copyProperties(capitalList, capitalHis);
		capitalHis.setAddTime(System.currentTimeMillis());
		capitalHis.setMoney(money);
		capitalHis.setFlag(CapitalFlag.Renew.getValue());
		int rowEffected = tbEntMemberIdentifyCapitalHisMapper.insertSelective(capitalHis);
		if (rowEffected != 1) {
			throw new BusinessDataException(BusinessMessages.RECHARGE_UPGRADE_VERSION_ERROR);
		}
	}
	
	

}
